<template>
  <div class="favorites-page">
    <!-- 顶部导航栏 -->
    <Header />
    
    <div class="main-content">
      <div class="container">
        <!-- 面包屑导航 -->
        <div class="breadcrumb">
          <a-breadcrumb>
            <a-breadcrumb-item>
              <a @click="goHome">{{ $t('nav.home') }}</a>
            </a-breadcrumb-item>
            <a-breadcrumb-item>{{ $t('nav.favorites') }}</a-breadcrumb-item>
          </a-breadcrumb>
        </div>
        
        <!-- 页面标题 -->
        <div class="page-header">
          <h1>{{ $t('favorites.title') }}</h1>
          <p>{{ $t('favorites.totalItems') || '共' }} {{ favorites.length }} {{ $t('cart.items') }}</p>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <a-spin size="large" />
          <p>正在加载收藏列表...</p>
        </div>
        
        <!-- 收藏列表 -->
        <div v-else-if="favorites.length > 0" class="favorites-content">
          <!-- 操作栏 -->
          <div class="actions-bar">
            <div class="left-actions">
              <a-checkbox 
                v-model:checked="selectAll" 
                @change="handleSelectAll"
              >
                全选
              </a-checkbox>
              <span class="selected-count" v-if="selectedItems.length > 0">
                已选择 {{ selectedItems.length }} 件商品
              </span>
            </div>
            <div class="right-actions">
              <a-button 
                v-if="selectedItems.length > 0"
                danger 
                @click="removeSelected"
                :loading="removing"
              >
                删除选中
              </a-button>
              <a-button @click="clearAll" :loading="clearing">
                清空收藏
              </a-button>
            </div>
          </div>
          
          <!-- 商品网格 -->
          <div class="favorites-grid">
            <div 
              v-for="favorite in favorites" 
              :key="favorite.id" 
              class="favorite-item"
              :class="{ selected: selectedItems.includes(favorite.id) }"
            >
              <!-- 选择框 -->
              <div class="item-checkbox">
                <a-checkbox 
                  v-model:checked="selectedItems" 
                  :value="favorite.id"
                />
              </div>
              
              <!-- 商品图片 -->
              <div class="item-image" @click="goToProduct(favorite.id)">
                <img :src="getProductImage(favorite)" :alt="favorite.name" />
              </div>
              
              <!-- 商品信息 -->
              <div class="item-info">
                <h3 class="item-name" @click="goToProduct(favorite.id)">
                  {{ favorite.name }}
                </h3>
                <p class="item-description">{{ favorite.description }}</p>
                
                <!-- 价格信息 -->
                <div class="item-price">
                  <span class="current-price">¥{{ favorite.price }}</span>
                  <span v-if="favorite.originalPrice > favorite.price" class="original-price">
                    ¥{{ favorite.originalPrice }}
                  </span>
                </div>
                
                <!-- 评分信息 -->
                <div class="item-rating">
                  <a-rate :value="favorite.rating" disabled allow-half size="small" />
                  <span class="rating-text">{{ favorite.rating }}</span>
                  <span class="review-count">({{ favorite.reviews }}条评价)</span>
                </div>
                
                <!-- 库存信息 -->
                <div class="item-stock">
                  <span v-if="favorite.stock > 0" class="in-stock">库存: {{ favorite.stock }}件</span>
                  <span v-else class="out-of-stock">暂时缺货</span>
                </div>
                
                <!-- 操作按钮 -->
                <div class="item-actions">
                  <a-button 
                    type="primary" 
                    size="small"
                    :disabled="favorite.stock <= 0"
                    @click="addToCart(favorite)"
                  >
                    <ShoppingCartOutlined />
                    加入购物车
                  </a-button>
                  <a-button 
                    size="small"
                    @click="goToProduct(favorite.id)"
                  >
                    查看详情
                  </a-button>
                  <a-button 
                    size="small" 
                    danger
                    @click="removeFavorite(favorite.id)"
                  >
                    取消收藏
                  </a-button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 分页 -->
          <div class="pagination-container" v-if="total > pageSize">
            <a-pagination
              v-model:current="currentPage"
              v-model:pageSize="pageSize"
              :total="total"
              :show-size-changer="true"
              :show-quick-jumper="true"
              :show-total="(total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`"
              @change="handlePageChange"
              @showSizeChange="handlePageSizeChange"
            />
          </div>
        </div>
        
        <!-- 空状态 -->
        <div v-else class="empty-state">
          <HeartOutlined class="empty-icon" />
          <h3>暂无收藏商品</h3>
          <p>您还没有收藏任何商品，快去发现心仪的商品吧！</p>
          <div class="empty-actions">
            <a-button type="primary" @click="goToProducts">
              去购物
            </a-button>
            <a-button @click="goHome">
              返回首页
            </a-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部信息 -->
    <Footer />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { message, Modal } from 'ant-design-vue'
import { ShoppingCartOutlined, HeartOutlined } from '@ant-design/icons-vue'
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import { favoriteApi } from '@/api'

// 使用Vuex store和Vue Router
const store = useStore()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const removing = ref(false)
const clearing = ref(false)
const favorites = ref([])
const selectedItems = ref([])
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 计算属性
const selectAll = computed({
  get: () => selectedItems.value.length === favorites.value.length && favorites.value.length > 0,
  set: (value) => {
    if (value) {
      selectedItems.value = favorites.value.map(item => item.id)
    } else {
      selectedItems.value = []
    }
  }
})

// 方法
const loadFavorites = async () => {
  loading.value = true
  
  try {
    const response = await favoriteApi.getFavorites()
    
    if (response.code === 200) {
      favorites.value = response.data
      total.value = response.data.length
      console.log('收藏列表加载成功:', response.data)
    } else {
      message.error(response.message || '加载收藏列表失败')
    }
  } catch (error) {
    console.error('加载收藏列表失败:', error)
    message.error('加载收藏列表失败，请重试')
  } finally {
    loading.value = false
  }
}

const getProductImage = (product) => {
  // 如果商品有images数组，使用第一张图片
  if (product.images && product.images.length > 0) {
    return product.images[0]
  }
  // 如果商品有image字段，使用image
  if (product.image) {
    return product.image
  }
  // 默认图片
  return 'https://picsum.photos/300/300?random=999'
}

const handleSelectAll = (checked) => {
  if (checked) {
    selectedItems.value = favorites.value.map(item => item.id)
  } else {
    selectedItems.value = []
  }
}

const removeFavorite = async (productId) => {
  try {
    const response = await favoriteApi.removeFavorite(productId)
    
    if (response.code === 200) {
      favorites.value = favorites.value.filter(item => item.id !== productId)
      selectedItems.value = selectedItems.value.filter(id => id !== productId)
      total.value = favorites.value.length
      message.success('已取消收藏')
    } else {
      message.error(response.message || '取消收藏失败')
    }
  } catch (error) {
    console.error('取消收藏失败:', error)
    message.error('取消收藏失败，请重试')
  }
}

const removeSelected = async () => {
  if (selectedItems.value.length === 0) {
    message.warning('请选择要删除的商品')
    return
  }
  
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedItems.value.length} 件商品吗？`,
    onOk: async () => {
      removing.value = true
      
      try {
        // 批量删除选中的商品
        for (const productId of selectedItems.value) {
          await favoriteApi.removeFavorite(productId)
        }
        
        // 从列表中移除
        favorites.value = favorites.value.filter(item => !selectedItems.value.includes(item.id))
        selectedItems.value = []
        total.value = favorites.value.length
        
        message.success('删除成功')
      } catch (error) {
        console.error('批量删除失败:', error)
        message.error('删除失败，请重试')
      } finally {
        removing.value = false
      }
    }
  })
}

const clearAll = async () => {
  if (favorites.value.length === 0) {
    message.warning('收藏列表已为空')
    return
  }
  
  Modal.confirm({
    title: '确认清空',
    content: '确定要清空所有收藏商品吗？此操作不可恢复。',
    onOk: async () => {
      clearing.value = true
      
      try {
        // 清空所有收藏
        favorites.value = []
        selectedItems.value = []
        total.value = 0
        
        message.success('收藏列表已清空')
      } catch (error) {
        console.error('清空收藏失败:', error)
        message.error('清空失败，请重试')
      } finally {
        clearing.value = false
      }
    }
  })
}

const addToCart = (product) => {
  if (product.stock <= 0) {
    message.warning('该商品暂时缺货')
    return
  }
  
  store.dispatch('cart/addToCart', {
    ...product,
    quantity: 1
  })
  
  message.success('已添加到购物车')
}

const goToProduct = (productId) => {
  router.push(`/product/${productId}`)
}

const goToProducts = () => {
  router.push('/products')
}

const goHome = () => {
  router.push('/')
}

const handlePageChange = (page) => {
  currentPage.value = page
  // 这里可以重新加载对应页的数据
}

const handlePageSizeChange = (current, size) => {
  currentPage.value = 1
  pageSize.value = size
  // 这里可以重新加载数据
}

// 生命周期
onMounted(() => {
  loadFavorites()
})
</script>

<style scoped>
.favorites-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.main-content {
  flex: 1;
  padding: 20px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.breadcrumb {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.page-header {
  background: white;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.page-header h1 {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin: 0 0 10px 0;
}

.page-header p {
  color: #666;
  margin: 0;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-container p {
  margin-top: 15px;
  color: #666;
}

.favorites-content {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.actions-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.left-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.selected-count {
  color: #666;
  font-size: 14px;
}

.right-actions {
  display: flex;
  gap: 10px;
}

.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
}

.favorite-item {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  position: relative;
}

.favorite-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.favorite-item.selected {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.item-checkbox {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  padding: 2px;
}

.item-image {
  height: 200px;
  overflow: hidden;
  cursor: pointer;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.item-image:hover img {
  transform: scale(1.05);
}

.item-info {
  padding: 15px;
}

.item-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0 0 8px 0;
  line-height: 1.4;
  cursor: pointer;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.item-name:hover {
  color: #1890ff;
}

.item-description {
  font-size: 14px;
  color: #666;
  margin: 0 0 10px 0;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.item-price {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.current-price {
  font-size: 18px;
  font-weight: bold;
  color: #ff4d4f;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.item-rating {
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 8px;
}

.rating-text {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.review-count {
  font-size: 12px;
  color: #999;
}

.item-stock {
  margin-bottom: 12px;
}

.in-stock {
  color: #52c41a;
  font-size: 14px;
}

.out-of-stock {
  color: #ff4d4f;
  font-size: 14px;
}

.item-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.item-actions .ant-btn {
  flex: 1;
  min-width: 80px;
}

.pagination-container {
  padding: 20px;
  text-align: center;
  border-top: 1px solid #f0f0f0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  color: #d9d9d9;
  margin-bottom: 20px;
}

.empty-state h3 {
  font-size: 20px;
  color: #333;
  margin: 0 0 10px 0;
}

.empty-state p {
  color: #666;
  margin: 0 0 20px 0;
}

.empty-actions {
  display: flex;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    padding: 15px 0;
  }
  
  .container {
    padding: 0 15px;
  }
  
  .favorites-grid {
    grid-template-columns: 1fr;
    gap: 15px;
    padding: 15px;
  }
  
  .actions-bar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .left-actions,
  .right-actions {
    justify-content: center;
  }
  
  .item-actions {
    flex-direction: column;
  }
  
  .item-actions .ant-btn {
    width: 100%;
  }
}
</style> 